package com.rzt.cft.service.uc.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rzt.cft.entity.uc.UcAssetStatistics;
import com.rzt.cft.mapper.uc.UcAssetStatisticsMapper;
import com.rzt.cft.param.uc.UcAssetStatisticsParam;
import com.rzt.cft.service.uc.IUcAssetStatisticsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * <p>
 * 用户-资产信息统计 服务实现类
 * </p>
 *
 * @author zhongzhong
 * @since 2020-03-15
 */
@Service
public class UcAssetStatisticsServiceImpl extends ServiceImpl<UcAssetStatisticsMapper, UcAssetStatistics> implements IUcAssetStatisticsService {

    @Override
    @Transactional
    public Boolean addAssetStatistics(UcAssetStatisticsParam param) {
        //先查询老的统计
        QueryWrapper<UcAssetStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", param.getUserId());
        queryWrapper.eq("current", true);
        UcAssetStatistics old = baseMapper.selectOne(queryWrapper);
        //如果有就先改为false,然后赋值到新的对象
        UcAssetStatistics ucAssetStatistics = new UcAssetStatistics();
        ucAssetStatistics.setCurrent(true);
        BigDecimal accumulationInjection = BigDecimal.ZERO;
        BigDecimal accumulationRebate = BigDecimal.ZERO;
        BigDecimal accumulationIntegral = BigDecimal.ZERO;
        if (Objects.nonNull(old)) {
            accumulationInjection = old.getAccumulationInjection();
            accumulationRebate = old.getAccumulationRebate();
            accumulationIntegral = old.getAccumulationIntegral();
            old.setCurrent(false);
            baseMapper.updateById(old);
        }
        //如果没有就新建插入数据
        accumulationInjection = param.getAccumulationInjection() == null ? accumulationInjection : accumulationInjection.add(param.getAccumulationInjection());
        accumulationRebate = param.getAccumulationRebate() == null ? accumulationRebate : accumulationRebate.add(param.getAccumulationRebate());
        accumulationIntegral = param.getAccumulationIntegral() == null ? accumulationIntegral : accumulationIntegral.add(param.getAccumulationIntegral());
        ucAssetStatistics.setUserId(param.getUserId());
        ucAssetStatistics.setAccumulationInjection(accumulationInjection);
        ucAssetStatistics.setAccumulationIntegral(accumulationIntegral);
        ucAssetStatistics.setAccumulationRebate(accumulationRebate);
        int insertCount = baseMapper.insert(ucAssetStatistics);

        return retBool(insertCount);
    }
}
